package archivemanagement;

import static com.google.common.base.Throwables.propagate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.UUID;

import metagrammar.Operator;

import com.google.inject.Inject;

public class OperatorManager implements ArchiveManager<UUID, Operator> {
    
    private final ArrayList<OperatorArchive> libraries;
    
    @Inject
    private OperatorManager(OperatorArchive... operatorLibraries)
    {
        libraries = new ArrayList<OperatorArchive>(Arrays.asList(operatorLibraries));
    }
    
    @Override
    public Operator load(UUID key)
    {
        for(OperatorArchive lib : libraries) {
            Operator operator;
            try {
                operator = lib.loadOperator(key);
                if(operator != null) {
                    return operator;
                }
            }
            catch(IOException e) {
                propagate(e);
            }
        }
        return null;
    }
    
    @Override
    public void add(Operator value)
    {
        for(OperatorArchive lib : libraries) {
            try {
                lib.writeOperator(value);
            }
            catch(IOException e) {
                propagate(e);
            }
        }
    }
    
    @Override
    public int update(Operator value)
    {
        int updatedLibraries = 0;
        for(OperatorArchive lib : libraries) {
            try {
                if(lib.containsOperator(value.getId())) {
                    lib.writeOperator(value);
                    updatedLibraries++;
                }
            }
            catch(IOException e) {
                propagate(e);
            }
        }
        return updatedLibraries;
    }
    
    @Override
    public Collection<Operator> loadAll()
    {
        ArrayList<Operator> operators = new ArrayList<Operator>();
        for(OperatorArchive lib : libraries) {
            try {
                operators.addAll(lib.loadAllOperators());
            }
            catch(IOException e) {
                propagate(e);
            }
        }
        return operators;
    }
}